<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAdddialog">添加商品</el-button>
        </el-col>
      </el-row>
      <tree-grid
        :data="catelist"
        :columns="columns"
        :show-index="true"
        :expand-type="false"
        :selection-type="false"
        :border="true"
        :show-row-hover="false"
      >
        <!-- 是否有效列 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!-- 排序列 -->
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作列 -->
        <template slot="options" slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" @click="showEditdialog(scope.row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" @click="deleteCate(scope.row)">删除</el-button>
        </template>
      </tree-grid>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加商品对话框 -->
    <el-dialog title="添加商品" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="addCateName"
            :options="parentCaselist"
            :props="addCateProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%" @close="eidtDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 请求数据
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      // 商品数据
      catelist: [],
      // 树状表格属性
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 将当前列定义为模板列
          type: 'template',
          // 表示当前列使用模板名称
          template: 'isok'
        },
        {
          label: '排序',
          // 将当前列定义为模板列
          type: 'template',
          // 表示当前列使用模板名称
          template: 'order'
        },
        {
          label: '操作',
          // 将当前列定义为模板列
          type: 'template',
          // 表示当前列使用模板名称
          template: 'options'
        }
      ],
      //   控制对话框显示
      dialogVisible: false,
      //   对话框数据
      addForm: {
        // 将要添加的分类名称
        cat_name: '',
        // 父级分类的id
        cat_pid: 0,
        // 分类的等级，默认要添加的是1级分类
        cat_level: 0
      },
      // 表单校验规则
      addFormRules: {
        cat_name: [
          {
            required: true,
            message: '请填写分类名称',
            triggle: 'blur'
          }
        ]
      },
      // 级联选择器存放id值
      addCateName: [],
      // 获取到的数据
      parentCaselist: [],
      // 配置选项
      addCateProps: {
        expandTrigger: 'hover',
        checkStrictly: 'true',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },

      // 编辑商品对话框
      // 显示隐藏
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        cat_name: {
          required: 'true',
          message: '请输入分类名称',
          triggle: 'blur'
        }
      },
      editCateId: ''
    }
  },
  created() {
    this.getCatelist()
  },
  methods: {
    // 获取商品数据
    async getCatelist() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.catelist = res.data.result
      this.total = res.data.total
    },
    // 分页
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getCatelist()
    },
    handleCurrentChange(newsize) {
      this.queryInfo.pagenum = newsize
      this.getCatelist()
    },
    // 对话框
    showAdddialog() {
      this.getParentCaselist()
      this.dialogVisible = true
    },
    // 获取对话框父级数据
    async getParentCaselist() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('数据请求失败！')
      }
      this.parentCaselist = res.data
    },
    handleChange(value) {
      console.log(value)
      // 若长度不为0， 则已经选中
      // 反之则没选中
      // 修改数据值
      if (this.addCateName.length > 0) {
        this.addForm.cat_pid = this.addCateName[this.addCateName.length - 1]
        this.addForm.cat_level = this.addCateName.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    // 点击按钮添加新分类
    addCate() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功！')
        this.getCatelist()
        this.dialogVisible = false
      })
    },
    // 监听关闭
    dialogClose() {
      this.$refs.addFormRef.resetFields()
      this.addCateName = []
      this.addForm.cat_level = 0
      this.addForm.cat_pid = 0
    },
    // 编辑商品对话框
    async showEditdialog(cate) {
      const { data: res } = await this.$http.get('categories/' + cate.cat_id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      this.editForm = res.data
      // 保存当前id值，方便提交修改数据使用
      this.editCateId = cate.cat_id
      this.editDialogVisible = true
      console.log(cate.cat_id)
      console.log(res)
    },
    // 提交修改信息
    async editCate() {
      const { data: res } = await this.$http.put(
        'categories/' + this.editCateId,
        this.editForm
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('数据更新失败！')
      }
      this.$message.success('数据更新成功！')
      this.getCatelist()
      this.editDialogVisible = false
    },
    // 监听对话框关闭，清除表单数据
    eidtDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除
    async deleteCate(cate) {
      const confirmResult = await this.$confirm(
        '请问是否要永久删除该用户',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + cate.cat_id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getCatelist()
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
